package com.lagou.edu.factory;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class  BeanFactory {
    //对象容器
    private static Map objectMap = new HashMap<>();

    static {
        //1.读取配置文件到内存中
        InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
        //2.解析XML，利用反射实例化对象
        try {
            //获取<bean></bean>标签
            Document document = new SAXReader().read(in);
            Element root = document.getRootElement();
            List<Element> elements = root.selectNodes("//bean");
            //遍历标签，获取id和class属性，实例化对象，存储到对象容器中
            for(Element ele : elements) {
                String id = ele.attributeValue("id");
                String clazz = ele.attributeValue("class");
                Object obj = Class.forName(clazz).newInstance();
                objectMap.put(id,obj);
            }
            //3.读取propertis标签，设置对象间依赖关系
            List<Element> propEles = root.selectNodes("//property");
            for(Element ele : propEles) {
                //获取被依赖对象
                String name = ele.attributeValue("name");
                String ref = ele.attributeValue("ref");
                Object obj = objectMap.get(ref);

                //获取父节点对应对象
                Element parent = ele.getParent();
                String id = parent.attributeValue("id");
                Object parentObj = objectMap.get(id);

                //利用反射setter方法设置依赖关系
                Method[] methods = parentObj.getClass().getMethods();
                for(Method method : methods) {
                    if("set".concat(name).equalsIgnoreCase(method.getName())) {
                        method.invoke(parentObj,obj);
                        break;
                    }
                }
                objectMap.put(id,parentObj);
            }
        } catch (DocumentException | ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据获取对象
     * @param id
     * @return
     */
    public static Object getBean(String id) {
        if(null == id || "".equals(id.trim())) {
           return null;
        }
        return objectMap.get(id);
    }
}
